<template>
  <div>
    <el-form ref="userFormRef" v-loading="formLoading" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="form.nickName" placeholder="请输入用户昵称" maxlength="30" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="归属部门" prop="deptId">
            <el-tree-select v-model="form.deptId" v-loading="deptLoading" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children', disabled: 'disabled' }" value-key="id" placeholder="请选择归属部门" check-strictly @change="handleDeptChange" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item v-if="form.userId == undefined" label="用户名称" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入用户名称" maxlength="30" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="form.userId == undefined" label="用户密码" prop="password">
            <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户性别">
            <el-select v-model="form.sex" placeholder="请选择">
              <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="岗位">
            <el-select v-model="form.postIds" multiple placeholder="请选择">
              <el-option
                v-for="item in postOptions"
                :key="item.postId"
                :label="item.postName"
                :value="item.postId"
                :disabled="item.status == '1'"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色" prop="roleIds">
            <el-select v-model="form.roleIds" filterable multiple placeholder="请选择">
              <el-option
                v-for="item in roleOptions"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
                :disabled="item.status == '1'"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="所有项目" prop="allProjectsFlag">
            <el-switch v-model="form.allProjectsFlag" active-value="0" inactive-value="1" @change="handleAllProjectsFlagChange()"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="项目权限" prop="parkIds">
            <el-select v-model="form.parkIds" filterable multiple placeholder="请选择" :disabled="form.allProjectsFlag === '0'">
              <el-option v-for="item in parkOptions" :key="item.parkInfoId" :label="item.parkName" :value="item.parkInfoId" ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <div style="display: flex; justify-content: center; align-items: center;">
      <el-button type="primary" :loading="butLoading" :disabled="butLoading" @click="submitForm">确 定</el-button>
      <el-button @click="emit('close');">取 消</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import api from '@/api/system/user';
import { DeptVO } from '@/api/system/dept/types';
import { RoleVO } from '@/api/system/role/types';
import { PostVO } from '@/api/system/post/types';
import { userparkVO } from '@/api/system/userPark/types';
import { UserForm, UserQuery } from '@/api/system/user/types';
import { treeselect } from '@/api/system/dept';
import { optionselect } from '@/api/system/post';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { sys_normal_disable, sys_user_sex } = toRefs<any>(proxy?.useDict('sys_normal_disable', 'sys_user_sex'));
const userFormRef = ref<ElFormInstance>();

const emit = defineEmits(['close', 'success']);
const props = defineProps({
  userId: {
    type: Number,
    default: undefined
  }
});

const initFormData: UserForm = {
  userId: undefined,
  deptId: undefined,
  userName: '',
  nickName: undefined,
  password: '',
  phonenumber: undefined,
  email: undefined,
  sex: undefined,
  status: '0',
  remark: '',
  postIds: [],
  roleIds: [],
  parkIds: [],
  allProjectsFlag: '1'
};

const initData: PageData<UserForm, UserQuery> = {
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: '',
    nickName: null,
    phonenumber: '',
    status: '',
    deptId: '',
    roleId: ''
  },
  rules: {
    userName: [
      { required: true, message: '用户名称不能为空', trigger: 'blur' },
      {
        min: 2,
        max: 20,
        message: '用户名称长度必须介于 2 和 20 之间',
        trigger: 'blur'
      }
    ],
    nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
    password: [
      { required: true, message: '用户密码不能为空', trigger: 'blur' },
      {
        min: 5,
        max: 20,
        message: '用户密码长度必须介于 5 和 20 之间',
        trigger: 'blur'
      },
      { pattern: /^[^<>"'|\\]+$/, message: '不能包含非法字符：< > " \' \\\ |', trigger: 'blur' }
    ],
    email: [
      {
        type: 'email',
        message: '请输入正确的邮箱地址',
        trigger: ['blur', 'change']
      }
    ],
    phonenumber: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur'
      }
    ],
    roleIds: [{ required: true, message: '用户角色不能为空', trigger: 'blur' }],
    parkIds: [
      {
        validator: (rule: any, value: any, callback: any) => {
          if (form.value.allProjectsFlag === '1' && (!value || value.length === 0)) {
            callback(new Error('项目权限不能为空'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ]
  }
};
const data = reactive<PageData<UserForm, UserQuery>>(initData);

const { queryParams, form, rules } = toRefs<PageData<UserForm, UserQuery>>(data);

/** 修改按钮操作 */
const formLoading = ref(false);
const postOptions = ref<PostVO[]>([]);
const roleOptions = ref<RoleVO[]>([]);
const parkOptions = ref<userparkVO[]>([]);
const updateInfo = async (row?: UserForm) => {
  formLoading.value = true;
  reset();
  const { data } = await api.getUser(props.userId).finally(() => { formLoading.value = false; })
  await initTreeData();
  Object.assign(form.value, data.user);
  postOptions.value = data.posts;
  roleOptions.value = data.roles;
  parkOptions.value = data.parks;
  form.value.postIds = data.postIds;
  form.value.roleIds = data.roleIds;
  form.value.parkIds = data.parkIds;
  form.value.password = '';
  if (form.value.allProjectsFlag === '0') {
    form.value.parkIds = [];
  }
};

const deptOptions = ref<DeptVO[]>([]);
/** 查询部门下拉树结构 */
const deptLoading = ref(false);
const getTreeSelect = async () => {
  deptLoading.value = true;
  const res = await api.deptTreeSelect().finally(() => { deptLoading.value = false; });
  deptOptions.value = res.data;
};

/** 初始化部门数据 */
const initTreeData = async () => {
  // 判断部门的数据是否存在，存在不获取，不存在则获取
  if (deptOptions.value === undefined) {
    const { data } = await treeselect();
    deptOptions.value = data;
  }
};

/** 提交按钮 */
const butLoading = ref(false);
const submitForm = () => {
  userFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      butLoading.value = true;
      if (form.value.allProjectsFlag === '0') {
        form.value.parkIds = [];
      }
      await api.updateUser(form.value).finally(() => { butLoading.value = false; });
      proxy?.$modal.msgSuccess('操作成功');
      emit('close');
      emit('success', form.value);
    }
  });
};

/** 重置表单 */
const reset = () => {
  userFormRef.value?.resetFields();
};

onMounted(() => {
  updateInfo()
  getTreeSelect(); // 初始化部门数据
});

async function handleDeptChange(value: number | string) {
  const response = await optionselect(value);
  postOptions.value = response.data;
  form.value.postIds = [];
}

/** 触发全部园区事件事件**/
const handleAllProjectsFlagChange = () => {
  if (form.value.allProjectsFlag === '0') {
    form.value.parkIds = [];
  }
};

</script>

<style scoped lang="scss">

</style>
